from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse
from django.conf import settings
import re


class RbacMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 获取当前访问的url
        current_url = request.path_info

        # 白名单处理
        for reg in settings.VALID_URL:
            if re.match(reg, current_url):
                return None

        # 从session中获取权限列表
        permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY)
        if not permission_dict:
            # 还没登录，跳转到登录页面
            return redirect("/login/")

        request.breadcrumb_list = [{"title": "首页", "url": "/"}]

        flag = False
        for item in permission_dict.values():
            id = item["id"]
            pid = item["pid"]
            pname = item['pname']

            reg = "^%s$" % item.get("url")
            if re.match(reg, current_url):
                flag = True
                if pid:
                    request.current_menu_id = pid
                    request.breadcrumb_list.extend([
                        {'title': permission_dict[pname]["title"], 'url': permission_dict[pname]["url"]},
                        {'title': item["title"], 'url': item["url"]}
                    ])
                else:
                    request.current_menu_id = id
                    request.breadcrumb_list.extend([{'title': item["title"], 'url': item["url"]}])
                break

        if not flag:
            return HttpResponse("无权访问")
